<template>
  <div class="file-browse">
    <el-card class="box-card">
      <div class="file-list">
        <el-table
          :data="fileList"
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            prop="fileName"
            label="文件名称"
            width="200"
          >
            <template #default="scope">
              <el-link type="primary" @click="downloadFile(scope.row)">
                {{ scope.row.fileName }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="fileSize"
            label="文件大小"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="uploadTime"
            label="上传时间"
            width="180"
          ></el-table-column>
          <el-table-column
            label="操作"
            width="100"
          >
            <template #default="scope">
              <el-button type="text" @click="downloadFile(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "FileBrowse",
  data() {
    return {
      fileList: [], // 文件列表
    };
  },
  created() {
    this.fetchFileList(); // 在组件创建时获取文件列表
  },
  methods: {
    // 获取文件列表
    fetchFileList() {
      this.$axios.get("/api/file/list") // 替换为你的文件列表接口
        .then((response) => {
          if (response.code === 200) {
            this.fileList = response.data.map((file) => {
              return {
                fileName: file.name,
                fileSize: this.formatSize(file.size),
                uploadTime: file.uploadTime,
                fileUrl: file.url, // 文件的下载地址
              };
            });
          } else {
            this.$message.error("获取文件列表失败：" + response.msg);
          }
        })
        .catch((error) => {
          this.$message.error("获取文件列表失败：" + error.message);
        });
    },
    // 格式化文件大小
    formatSize(size) {
      if (size < 1024) return size + " B";
      else if (size < 1024 * 1024) return (size / 1024).toFixed(2) + " KB";
      else if (size < 1024 * 1024 * 1024) return (size / 1024 / 1024).toFixed(2) + " MB";
      else return (size / 1024 / 1024 / 1024).toFixed(2) + " GB";
    },
    // 下载文件
    downloadFile(file) {
      window.open(file.fileUrl, "_blank");
    },
    // 表格行样式
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return "warning-row";
      } else {
        return "success-row";
      }
    },
  },
};
</script>

<style scoped>
.file-browse {
  padding: 20px;
}
.box-card {
  margin: 20px;
}
</style>
